import axios from 'axios'
import baseurl from '../http-config/config.js'
import requestMethod from '../http-config/request-method.js'
import { Message } from 'element-ui'
import { local } from '../../utils'

// config配置
const hostconfig = {
  baseURL: baseurl.host,
  timeout: 1000 * 6,
  withCredentials: true,
  // 下面两个属性，用来设置，请求失败或者超时，自动重新请求的次数和间隙时间
  retry: 1, // 请求次数
  retryInterval: 1000, // 求期间隙
}

const hostRequest = axios.create(hostconfig)

//http request 拦截器
hostRequest.interceptors.request.use(
  config => {
    // 添加请求头
    const userinfo = local.get('userinfo_Token')
    config.headers.AcceptToken = userinfo && userinfo.token
    return config
  },
  error => {
    Message.error({
      message: '请求错误!!!',
      duration: 3000,
    })
    return Promise.reject(error)
  }
)

//http response 拦截器
hostRequest.interceptors.response.use(
  response => {
    // 这个是随便搞得 ，对于这个是要根据实际情况来定   实例一下
    switch (response.status) {
      case 200:
        if (response.data.code == 200) {
          console.log('response 拦截器')
          response = response.data
        }
        // if (response.data.code == 403) {
        //   setTimeout(() => {
        //     window.location.href = '/login'
        //   }, 500)
        // }
        break
      case 500:
        Message.error({
          message: '后台错误!!!',
          duration: 3000,
        })
        break
    }
    return response
  },
  error => {
    if (error.message.includes('timeout')) {
      // 判断请求异常信息中是否含有超时timeout字符串
      Message.error({
        message: '请求超时！',
        duration: 3000,
      })
      return Promise.reject(error) // reject这个错误信息
    }
    Message.error({
      message: '系统异常！',
      duration: 3000,
    })
    return Promise.reject(error)
  }
)

const hostrequest = new requestMethod(hostRequest)
export default hostrequest
